<template>
  <div class="home">
    
    <!-- 对话框组件 -->
    <div class="chat-container">
      <h2>小禾宝 聊天</h2>
      
      <!-- 聊天消息区域 -->
      <div class="chat-messages">
        <!-- 系统提示消息 -->
        <div class="system-message">
          我是小禾宝智能助手，有什么可以帮助您的吗？
        </div>
        <!-- {{ JSON.stringify(chatHistory) }} -->
        <!-- 聊天历史记录 -->
        <div v-for="(chat, index) in chatHistory" :key="index" class="message-group">
          <!-- 用户消息 -->
          <div class="message user-message" v-if="chat.question">
            <img src="../assets/22.jpg" class="avatar" alt="用户头像">
            <div class="message-content-container">
              <div class="message-sender">您</div>
              <div class="message-content">{{ chat.question }}</div>
            </div>
          </div>
          
          <!-- AI回复 -->
          <div class="message ai-message">
            <img src="../assets/11.png" class="avatar" alt="AI头像">
            <div class="message-content-container">
              <div class="message-sender">小禾宝</div>
              <div class="message-content" v-html="md.render(chat.answer)"></div>
            </div>
          </div>
        </div>
        
        <!-- 流式响应展示 -->
        <div v-if="currentStream" class="message ai-message streaming">
          <img src="../assets/11.png" class="avatar" alt="AI头像">
          <div class="message-content-container">
            <div class="message-sender">小禾宝</div>
            <div class="message-content" v-html="md.render(currentStream)"></div>
          </div>
        </div>
      </div>
      
      <div class="dialog-content">
        <input
          type="text"
          v-model="inputValue"
          placeholder="请输入内容..."
          class="input-field"
          @keydown.enter="handleSubmit"
        />
        <button @click="handleSubmit" class="submit-button">提交</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import MarkdownIt from 'markdown-it';
const md = new MarkdownIt();
// 输入框数据绑定
const inputValue = ref('');
// 存储聊天记录，每个对象包含问题和答案
const chatHistory = ref([]);
// 存储当前流式响应
const currentStream = ref('');

// 处理提交事件
const handleSubmit =async () => {

  if (inputValue.value.trim()) {
    const endpoint = 'https://api.deepseek.com/chat/completions';
    const headers = {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${import.meta.env.VITE_DEEPSEEK_API_KEY}`
    };
    // 将输入值添加到提交数据数组
    const payload = {
    model: 'deepseek-chat',
    messages :[
    // {role: "system", content: "You are a helpful assistant."},
    {role: "user", content: inputValue.value.trim()}
    ],
    stream: true,
};
const response = await fetch(endpoint, {
    method: 'POST',
    headers: headers,
    body: JSON.stringify(payload)
});

if (!response.body) {
  console.error('Response body is not readable');
  return;
}

const reader = response.body.getReader();
const decoder = new TextDecoder();
currentStream.value = '';

while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  
  const chunk = decoder.decode(value, { stream: true });
  // 提取SSE格式中的内容
  const lines = chunk.split('\n');
  for (const line of lines) {
    if (line.trim().startsWith('data:')) {
      const data = line.replace('data:', '').trim();
      if (data === '[DONE]') break;
      
      try {
        const json = JSON.parse(data);
        if (json.choices && json.choices[0] && json.choices[0].delta && json.choices[0].delta.content) {
          currentStream.value += json.choices[0].delta.content;
        }
      } catch (e) {
        console.error('解析流数据出错:', e);
      }
    }
  }
}

// 立即清空输入框并添加用户消息
const userQuestion = inputValue.value.trim();
inputValue.value = '';

// 创建临时聊天记录
const tempChat = {
  question: userQuestion,
  answer: ''
};
chatHistory.value.push(tempChat);

// 只在收到有效响应内容时才更新答案
if (currentStream.value.trim()) {
  tempChat.answer = currentStream.value;
  currentStream.value = '';
}
  }
};
</script>

<style scoped>
.home {
  padding: 20px;
}

.chat-container {
  max-width: 800px;
  margin: 30px auto;
  border: 1px solid #e0e0e0;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  overflow: hidden;
}

.chat-messages {
  height: 500px;
  overflow-y: auto;
  padding: 20px;
  background-color: #f9fafb;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.chat-container h2 {
  margin: 0;
  padding: 16px 20px;
  background-color: #42b983;
  color: white;
  font-size: 18px;
  font-weight: 500;
}

.dialog-content {
  display: flex;
  gap: 10px;
  padding: 15px 20px;
  background-color: white;
  border-top: 1px solid #eee;
}

.input-field {
  flex: 1;
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  resize: none;
  min-height: 48px;
  max-height: 120px;
  line-height: 1.5;
}

.submit-button {
  padding: 0 20px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 24px;
  cursor: pointer;
  transition: background-color 0.3s;
  white-space: nowrap;
}

.input-field {
    flex: 1;
    padding: 12px 15px;
    border: 1px solid #ddd;
    border-radius: 24px;
    font-size: 14px;
    resize: none;
    min-height: 48px;
    max-height: 120px;
    line-height: 1.5;
    outline: none;
}

.input-field:focus {
    border-color: #42b983;
    box-shadow: 0 0 0 2px rgba(66, 185, 131, 0.2);
}

.submit-button {
  padding: 10px 20px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.submit-button:hover {
  background-color: #359469;
}

.streaming-data {
  margin-top: 20px;
  padding: 15px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  background-color: #f9f9f9;
}

.message {
  max-width: 100%;
  margin: 5px 0;
  padding: 10px 15px;
  border-radius: 18px;
  line-height: 1.5;
  display: flex;
  align-items: flex-start;
  gap: 10px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  flex-shrink: 0;
}

.avatar-placeholder {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #e5e7eb;
  flex-shrink: 0;
}

.message-content-container {
  flex: 1;
}

.user-message {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.ai-message {
  align-self: flex-start;
  background-color: white;
  border: 1px solid #e5e7eb;
}

.user-message .message-content {
  background-color: #42b983;
  color: white;
  border-radius: 18px 18px 4px 18px;
  padding: 12px 16px;
}

.ai-message .message-content {
  border-radius: 18px 18px 18px 4px;
  padding: 12px 16px;
}

.message-sender {
  font-size: 12px;
  margin-bottom: 4px;
  font-weight: 500;
  color: #666;
}

.system-message {
  align-self: center;
  background-color: #f0f0f0;
  padding: 8px 16px;
  border-radius: 16px;
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.streaming .message-content {
  animation: typing 1.4s infinite;
}

@keyframes typing {
  0% { opacity: 0.6; }
  50% { opacity: 1; }
  100% { opacity: 0.6; }
}

.submitted-data h3 {
  margin-bottom: 10px;
  color: #666;
}

.submitted-data ul {
  padding-left: 20px;
  margin: 0;
}

.submitted-data li {
  margin: 5px 0;
  color: #333;
}
</style>